import { getOpenIdByCodeApi, getUserLoginInfoApi, getUnionIdApi, getMemberIdByOpenIdApi, tencentOpenIdConnectApi } from '../../api/index'
import { STORAGE_KEY } from '../../utils/storage.js';
import { Logger } from '../../utils/index'
const logger = new Logger()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    txOpenId: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    loading: false,
    shipConfig: {
      withCredentials: true,
      lang: 'zh_CN'
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loginSuccess: function(res) {
      const that = this
      wx.showLoading({
        title: '正在登录...'
      })
      if(res.type !== 'success') {
        wx.hideLoading()
        return
      }
      const data = res.detail

      that.getUnionIdByCode(data).then(userData => {
        const {openId, encryOpenId, aesOpenId, unionId, aesUnionId, memberId } = userData
        wx.setStorageSync(STORAGE_KEY.openId, openId)
        wx.setStorageSync(STORAGE_KEY.encryOpenId, encryOpenId)
        wx.setStorageSync(STORAGE_KEY.aesOpenId, aesOpenId)
        wx.setStorageSync(STORAGE_KEY.unionId, unionId)
        wx.setStorageSync(STORAGE_KEY.aesUnionId, aesUnionId)
        wx.setStorageSync(STORAGE_KEY.wxMemberId, memberId)

        that.getMemberIdByOpenId(openId, unionId).then(memberData => {
          wx.setStorageSync(STORAGE_KEY.memberId, memberData.memberid)
        })

        
        const txOpenId = that.properties.txOpenId
        if(openId && unionId && txOpenId) {
          // 腾讯测试openid 和同程船票绑定
          tencentOpenIdConnectApi({
            ShipOpenId: openId,
            ShipUnionId: unionId,
            TcentOpenId: txOpenId,
            tcentUnionId: "",
          }).then(response => {
            if(!response) {
              logger.warn("绑定失败")
              return
            }
            logger.info("确定绑定关系")
          })
        }

        that.triggerEvent('success', userData)
        wx.hideLoading()

      }).catch(err => {
        console.log(err)
        wx.hideLoading()
      })

    },
    
    // 通过code获取openId  暂时用不到
    getOpenIdByCode({code}){
      let that = this
      // 会员来源（0：拼团小程序,1：船票通小程序,2：支付宝小程序,3：微信H5,4：M站,5：APP,6：GzklApplet,7:HanlgApplet,8:YingKApplet,9:ZhongTieApplet,10:zhgsApplet,11:jzylApplet）
      return getOpenIdByCodeApi({
        code,
        UserFrom: 1
      }).then(res => {
        if (res.data && res.data.Code == 10000) {
          wx.setStorageSync(STORAGE_KEY.openId, res.data.Data.OpenId)
        }
      })
    },

    // 通过code 获取openId, unionId
    getUnionIdByCode(data) {
      const that = this
      return getUserLoginInfoApi({
        code: data.code,
        scene: ''
      }).then(response => {
        if(!response || response.status !== 200) {
          return
        }
        const {openId, encryOpenId, aesOpenId, unionId, aesUnionId, memberId } = response.data
        
        if(!unionId) {

          // 没有 unionId 大概率是  在同城体系是 新用户 需要从解密数据中获取 UnionID
          return that.getUnionIdBySign(data, openId).then(_unionId => {
            
            let result = response.data
            result.unionId = _unionId
            return result
          })
        }
        return response.data
      })
    },

    // 从解密数据中获取 UnionID
    getUnionIdBySign({encryptedData, iv}, openId) {
      return getUnionIdApi({
        encryptData: encryptedData,
        openId,
        iv,
        appIdMap: 36
      }).then(response => {
        if(!response || response.status !== 200) {
          return
        }
        return response.data
      })
    },

    // 获取同程 memberId
    getMemberIdByOpenId: function(openId, unionId) {
      return getMemberIdByOpenIdApi({
        openId: openId,
        UnionId: unionId
      }).then(response => {
        if(!response || response.status !== 200) {
          return
        }

        if(response.data.ResCode) {
          return
        }


        return response.data.Body
      })
    }

  }
})
